package cn.jilian.front.service.impl;


import com.baidu.aip.ocr.AipOcr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;

import cn.jilian.front.domain.BizLicenseInfo;
import cn.jilian.front.service.BizlicenseService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component("bizLicenseFileHandler")
public class BizlicenseFileHandler implements BizlicenseService {

    @Autowired
    private AipOcr aipOcr;

    private ObjectMapper objectMapper = new ObjectMapper();

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final Map<String, String> bizLicenseMap = ImmutableMap.<String, String>builder()
            .put("单位名称", "orgName")
            .put("地址", "address")
            .put("证件编号", "licenseNo")
            .put("法人", "legalRepreName")
            .put("社会信用代码", "socialCreditCode")
            .put("有效期", "expireTime")
            .build();

    private BizLicenseInfo getBizLicenseInfo(JSONObject json){
    	if (!json.has("words_result")) return null;
        Map<String, String> rs = new HashMap<>();
        try {
            JSONObject result = json.getJSONObject("words_result");
            for (String key : bizLicenseMap.keySet()) {
                JSONObject n = result.getJSONObject(key);
                if (n != null) {
                	if(n.has("words")){
                		String v = n.getString("words");
                        if (StringUtils.isNotBlank(v)) {
                            String name = bizLicenseMap.get(key);
                            rs.put(name, v);
                        }
                	}
                    
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        BizLicenseInfo info = objectMapper.convertValue(rs, BizLicenseInfo.class);
        logger.debug("get baidu ocr result:{}", info);
        return info;
    }
    @Override
    public BizLicenseInfo handle(String path) {
        logger.debug("try scan bizlicense jpg from path: {}", path);
        JSONObject json = aipOcr.businessLicense(path, null);
        return getBizLicenseInfo(json);
    }

	@Override
	public BizLicenseInfo handle(byte[] data) {
		 logger.debug("try scan bizlicense jpg from byte data");
		JSONObject json = aipOcr.businessLicense(data, null);
		 return getBizLicenseInfo(json);
	}
}
